package com.bdqn.gulimall.product.web;


import com.bdqn.gulimall.product.entity.CategoryEntity;
import com.bdqn.gulimall.product.service.CategoryService;
import com.bdqn.gulimall.product.vo.Catelog2Vo;
import org.redisson.api.*;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Controller
public class IndexController {

    @Resource
    private CategoryService categoryService;

    @Resource
    private RedissonClient redisson;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @GetMapping({"/","/index.html"})
    public String indexPage(Model model){

        //TODO 1.查询所有的一级分类

        List<CategoryEntity> categoryEntityList = categoryService.getLevel1Categorys();
        model.addAttribute("categorys",categoryEntityList);
        return "index";
    }

    //index/catalog.json
    @ResponseBody
    @GetMapping("/index/catalog.json")
    public Map<Long, List<Catelog2Vo>> getCatalogJson(){
        Map<Long, List<Catelog2Vo>> map = categoryService.getCatalogJson();
        return map;
    }

    @ResponseBody
    @GetMapping("/hello")
    public String hello(){
        //获取一把锁
        RLock lock = redisson.getLock("lock");

        //加锁，并且使用锁
        /**
         * 如果不指定时间的话，redisson里也自带了默认的定时时间，并且在有效期过了3/1的时间，如果程序代码还在进行，并且会自动为锁更新时间
         * 如果指定了时间，redisson就不会为锁进行看门狗机制
         */
        lock.lock(30, TimeUnit.SECONDS);    //阻塞式等待，线程如果没有拿到锁，就会一直在这里进行等待，直至拿到锁为止
        try {
            System.out.println("加锁成功，执行业务代码"+Thread.currentThread().getId());
            Thread.sleep(30000);
        }catch (Exception e){

        }finally {
            //释放锁
            System.out.println("释放锁"+Thread.currentThread().getId());
            lock.unlock();
        }




        return "hello";
    }

    @ResponseBody
    @GetMapping("/write")
    public String Write(){
        RReadWriteLock readWriteLock = redisson.getReadWriteLock("rw-lock");
        RLock rLock = readWriteLock.writeLock();
        String s="";
        try {
            rLock.lock();
            Thread.sleep(30000);
            s = UUID.randomUUID().toString();
            stringRedisTemplate.opsForValue().set("uuid",s);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            rLock.unlock();
        }
        return s;
    }

    @ResponseBody
    @GetMapping("/read")
    public String read(){
        RReadWriteLock readWriteLock = redisson.getReadWriteLock("rw-lock");
        String uuid="";
        RLock rLock = readWriteLock.readLock();
        try {

            rLock.lock();
            uuid = stringRedisTemplate.opsForValue().get("uuid");
        }catch (Exception e){

        }finally {
            rLock.unlock();
        }
        return uuid;
    }

    @ResponseBody
    @GetMapping("/lockDoor")
    public String door() throws InterruptedException {
        RCountDownLatch door = redisson.getCountDownLatch("door");  //创建闭锁
        door.trySetCount(5);    //设置计数，达到5个之后，就关闭锁
        door.await();//等待计数条件为0
        return "放假了。。关门了";
    }

    @ResponseBody
    @GetMapping("/gogogo/{id}")
    public String gogogo(@PathVariable Long id) throws InterruptedException {
        RCountDownLatch door = redisson.getCountDownLatch("door");
        door.countDown();   //计数减一
        return id+"班放学了";
    }

    /**
     * 停车例子
     * 一共三个车库
     * @return
     * @throws InterruptedException
     */
    @ResponseBody
    @GetMapping("/pack")
    public String pack() throws InterruptedException {
        RSemaphore pack = redisson.getSemaphore("pack");
//        pack.acquire();     //占用一个，并且数量减一
        boolean b = pack.tryAcquire();

        return "ok"+b;
    }

    /**
     * 车子开走,不打算继续停车了
     * @return
     * @throws InterruptedException
     */
    @ResponseBody
    @GetMapping("/go")
    public String go() throws InterruptedException {
        RSemaphore pack = redisson.getSemaphore("pack");
        pack.release();     //释放一个，数量加一
        return "一辆车开走了";
    }



}
